#!/usr/bin/env node

// 标准舵机PWM信号测试
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);

console.log("🚗 开始舵机PWM信号测试...");

async function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

// 使用shell脚本生成精确的PWM信号
async function generatePWM(pin, dutyCycleMs, durationSec) {
  const periodMs = 20; // 50Hz = 20ms周期
  const highTimeMs = dutyCycleMs;
  const lowTimeMs = periodMs - dutyCycleMs;
  
  console.log(`📡 引脚${pin}: 高电平${highTimeMs}ms, 低电平${lowTimeMs}ms, 持续${durationSec}秒`);
  
  const cycles = Math.floor((durationSec * 1000) / periodMs);
  
  for (let i = 0; i < cycles; i++) {
    await execAsync(`gpio -g write ${pin} 1`);
    await sleep(highTimeMs);
    await execAsync(`gpio -g write ${pin} 0`);
    await sleep(lowTimeMs);
  }
}

async function testServo() {
  try {
    // 设置引脚为输出模式
    await execAsync(`gpio -g mode 13 out`);
    await execAsync(`gpio -g mode 12 out`);
    console.log("✅ 引脚13和12设置为输出模式");
    
    // 初始化为低电平
    await execAsync(`gpio -g write 13 0`);
    await execAsync(`gpio -g write 12 0`);
    
    console.log("\n🎯 开始舵机标准信号测试:");
    console.log("标准舵机PWM信号: 50Hz频率(20ms周期)");
    console.log("- 1.0ms 高电平 = -90度(或最小油门)");
    console.log("- 1.5ms 高电平 = 0度(或中性油门)"); 
    console.log("- 2.0ms 高电平 = +90度(或最大油门)");
    
    const tests = [
      { name: "电调(引脚13) - 中性位置", pin: 13, dutyCycle: 1.5, duration: 3 },
      { name: "电调(引脚13) - 前进慢速", pin: 13, dutyCycle: 1.6, duration: 3 },
      { name: "电调(引脚13) - 前进中速", pin: 13, dutyCycle: 1.8, duration: 3 },
      { name: "电调(引脚13) - 前进快速", pin: 13, dutyCycle: 2.0, duration: 3 },
      { name: "电调(引脚13) - 回到中性", pin: 13, dutyCycle: 1.5, duration: 2 },
      { name: "电调(引脚13) - 后退慢速", pin: 13, dutyCycle: 1.4, duration: 3 },
      { name: "电调(引脚13) - 后退中速", pin: 13, dutyCycle: 1.2, duration: 3 },
      { name: "电调(引脚13) - 后退快速", pin: 13, dutyCycle: 1.0, duration: 3 },
      { name: "电调(引脚13) - 最终中性", pin: 13, dutyCycle: 1.5, duration: 3 },
      
      { name: "舵机(引脚12) - 中心位置", pin: 12, dutyCycle: 1.5, duration: 3 },
      { name: "舵机(引脚12) - 右转30度", pin: 12, dutyCycle: 1.8, duration: 3 },
      { name: "舵机(引脚12) - 右转最大", pin: 12, dutyCycle: 2.0, duration: 3 },
      { name: "舵机(引脚12) - 回到中心", pin: 12, dutyCycle: 1.5, duration: 2 },
      { name: "舵机(引脚12) - 左转30度", pin: 12, dutyCycle: 1.2, duration: 3 },
      { name: "舵机(引脚12) - 左转最大", pin: 12, dutyCycle: 1.0, duration: 3 },
      { name: "舵机(引脚12) - 最终中心", pin: 12, dutyCycle: 1.5, duration: 3 }
    ];
    
    for (let i = 0; i < tests.length; i++) {
      const test = tests[i];
      console.log(`\n🔧 [${i+1}/${tests.length}] ${test.name}`);
      console.log(`   PWM: ${test.dutyCycle}ms 高电平，持续 ${test.duration} 秒`);
      
      await generatePWM(test.pin, test.dutyCycle, test.duration);
      
      // 停止信号
      await execAsync(`gpio -g write ${test.pin} 0`);
      
      console.log(`   ✅ 完成`);
      
      if (i < tests.length - 1) {
        console.log(`   ⏸️  暂停1秒...`);
        await sleep(1000);
      }
    }
    
    console.log("\n🛑 测试完成，停止所有PWM信号");
    await execAsync(`gpio -g write 13 0`);
    await execAsync(`gpio -g write 12 0`);
    
    console.log("\n✅ 舵机PWM测试完成！");
    console.log("\n🔍 观察结果:");
    console.log("1. 如果连接了电调，应该能听到蜂鸣声变化或看到电机转动");
    console.log("2. 如果连接了舵机，应该能看到舵机轴转动");
    console.log("3. 如果没有反应，请检查:");
    console.log("   - 硬件接线: 信号线连接到正确引脚");
    console.log("   - 电源供应: 电调/舵机是否有独立电源");
    console.log("   - 设备状态: 电调是否已校准，舵机是否损坏");
    
  } catch (error) {
    console.error("❌ 舵机测试失败:", error.message);
    
    // 确保清理
    try {
      await execAsync(`gpio -g write 13 0`);
      await execAsync(`gpio -g write 12 0`);
    } catch (e) {}
  }
}

testServo();